/*
 * @Author: 
 * @Date: 2022-02-24 16:20:22
 * @LastEditors: lqj
 * @LastEditTime: 2022-02-28 13:41:10
 * @Description: 级联地址组件
 */
import React, { useState, useEffect, useRef } from 'react'
import AreaCss from './styles/Area.module.less'
import { Button, Checkbox } from 'antd'
import VCheckBox from './VCkeckBox'
import './styles/ant.less';
import { setPopChild, getChildrenList, setTreeItem, changeChildItemsCheckedStatus, getCount, checkedLinkBy } from './utils'

export default function AreaCom() {
  const [notEdit] = useState(false)
  const useResult = useRef()
  const [all, setAll] = useState(false)
  const [hideItems] = useState([])
  const [treeList, setTree] = useState([])
  const [current, setCurrent] = useState([])
  const [currentSelectedInfo, setCurrentSelectedInfo] = useState({
    names: [],
    currentselectItems: []
  })

  const getAddress = () => {
    const treeMap = setPopChild(getChildrenList(4), 6)
    const currentMap = current.map(it => it)
    setAllItemsAddressShow(treeMap)
    setAllItemsAddrShowByChildren(treeMap)
    currentMap.forEach(it => {
      getCurrentParent(treeMap, it.parentCode)
      checkedLinkBy(treeMap, it.code)
    })
    getCount(treeMap)
    treeMap.forEach(item => {
      const showChildren = item.children.filter(it => it.show)
      const flag = (showChildren.filter(it => it.checked).length && showChildren.filter(it => !it.checked).length)
      item.checked = showChildren.every(it => it.checked)
      item.isIndeterminate = showChildren.some(it => it.isIndeterminate) || flag
    })
    const len = treeMap.filter(it => it.checked)
    if (len.length === treeMap.length) toogleAll()
    setTree(treeMap)
    setCurrent(currentMap)
  }
  useEffect(() => {
    getAddress()
  }, [])
  const setAllItemsAddrShowByChildren = (currentItems) => {
    currentItems.forEach(it => {
      if (it.children) {
        setAllItemsAddrShowByChildren(it.children)
      }
    })
  }
  const setAllItemsAddressShow = (currentItems) => {
    currentItems.forEach(it => {
      if (it.children) {
        setAllItemsAddressShow(it.children)
      }
      it.show = !hideItems.includes(it.code)
      it.checked = current.map(it => it.code).includes(it.code)
      it.count = 0
    })
  }
  const getCurrentParent = (tree, parentCode) => {
    for (let i = 0; i < tree.length; i++) {
      if (tree[i].code === parentCode) {
        const pItem = tree[i]
        const length = pItem.children.filter(it => {
          return (it.checked || it.isIndeterminate) && it.show
        }).length
        if (length === 0) {
          pItem.checked = false
          pItem.isIndeterminate = false
        } else if (pItem.children.filter(it => it.show).every(it => it.checked)) {
          pItem.checked = true
          pItem.isIndeterminate = false
        } else {
          pItem.checked = false
          pItem.isIndeterminate = true
        }
        if (pItem.parentCode) {
          getCurrentParent(treeList, pItem.parentCode)
        }
      } else {
        if (tree[i].children) getCurrentParent(tree[i].children, parentCode)
      }
    }
  }
  const getTreeItem = (data, arr) => {
    data.forEach(item => {
      const flag1 = item.show && item.checked && !item.children
      const flag2 = item.show && item.checked && item.children && item.children.every(_v => _v.show)
      if (flag1 || flag2) {
        item.parentCode ? arr.push(item) : arr.push(...item.children.filter(it => it.show))
      } else {
        if (item.show && item.children && (item.isIndeterminate || item.checked)) getTreeItem(item.children, arr)
      }
      useResult.current = arr
    })
  }
  const toogleAll = () => {
    const bool = !all
    const treeMap = [...treeList]
    for (let i = 0; i < treeMap.length; i++) {
      const it = treeMap[i]
      it.checked = bool
      it.isIndeterminate = false
      changeChildItemsCheckedStatus(bool, it)
    }
    getCount(treeMap)
    setAll(bool)
    setTree(treeMap)
    if (bool) {
      return setCurrentSelectedInfo({ names: treeList.filter(it => it.show).map(it => it.name), currentselectItems: [] })
    }
    setCurrentSelectedInfo({ names: [], currentselectItems: [] })
  }
  const submit = () => {
    const treeMap = [...treeList]
    getTreeItem(treeMap, [])
    setCurrentSelectedInfo({ names: currentSelectedInfo.names, currentselectItems: useResult.current })
  }
  const handleChange = (val, op) => {
    const treeMap = [...treeList]
    const checked = val.target.checked
    setTreeItem(checked, treeMap, op)
    changeChildItemsCheckedStatus(checked, op)
    getCurrentParent(treeMap, op.parentCode)
    getCount(treeMap)
    setTree(treeMap)
  }
  return (
    <div className={AreaCss.rArea}>
      {
        treeList.filter(it => it.show).map(op => {
          return <div key={op.code} className={op.children.filter(item => item.show).length > 0 ? AreaCss.onePiece: ''}>
            {
              op.children.filter(item => item.show).length > 0 ?
              <>
                <div className={AreaCss.left}>
                  <Checkbox
                    checked={op.checked}
                    disabled={notEdit}
                    indeterminate={op.isIndeterminate}
                    onChange={v => handleChange(v, op)}
                  >
                    {op.name}
                      <span className={AreaCss.count}>({op.count})</span>
                  </Checkbox>
                </div>
                <div className={AreaCss.right}>
                  {
                      op.children.map(p => {
                        return (<div key={p.code} className={p.show ? AreaCss.province : ''}>
                          <VCheckBox
                            node={p}
                            notEdit={notEdit}
                            tree={treeList}
                            currentSelectedInfo={currentSelectedInfo}
                            changeNode={handleChange} />
                        </div>)
                      })
                  }
                </div>
              </>
              :<></>
            }
          </div>
        })
      }

      <div className={AreaCss.areaBtns}>
        <Button disabled={notEdit} onClick={toogleAll}>
          { all ? '全部取消' : '全选' }
        </Button>
        <Button type="primary" disabled={notEdit} onClick={submit}>
          提交
        </Button>
      </div>
    </div>
  )
}
